<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>音乐搜索</title>
  <!-- Bootstrap 3.4.1 -->
  <link href="../../plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <!-- Font Awesome 图标 -->
  <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <style >
    @import url(search.css);
    @import url(../../css/nav.css);
    

  </style>
</head>
<body>
  
<div class="container">
  <div class="row md-6">
    <div class="col-lg-6">
      <div class="input-group" id="searchInput">
        <input type="text" class="form-control" id="searchQuery" placeholder="搜索歌曲...">
        <span class="input-group-btn">
          <button class="btn btn-default" type="button" id="searchButton">
            <span class="glyphicon glyphicon-search"></span>
          </button>
        </span>
      </div>
    </div>
  </div>

  <div class="row md-6" id="songList" style="display: none;">
    <div class="col-lg-12">
      <table class="table table-bordered">
        <thead>
          <tr>
            <th>歌曲名称</th>
            <th>歌手</th>
            <th>专辑</th>
            <th>时长</th>
          </tr>
        </thead>
        <tbody id="songs">
        </tbody>
      </table>
    </div>
  </div>
</div>
  
  <!-- Bootstrap 3 依赖 -->
  <script src="../../plugins/jquery/jquery.min.js"></script>
  <script src="../../plugins/bootstrap/js/bootstrap.min.js"></script>
  <script src="../../js/search.js"> </script>
<script>
  // search.js
  $(document).ready(function() {
    // 初始化事件监听
    initEventListeners();

    // 显示版本信息
    console.log('Music Search v1.0 initialized');
  });

  function initEventListeners() {
    // 搜索按钮点击事件
    $('#searchButton').click(function() {
      handleSearch();
    });

    // 新增歌曲行点击事件
    $(document).on('click', '.song-item', function() {
      const songId = $(this).data('songId');
      window.location.href = `/dev/view/songDetail/player.html?songId=${songId}`; // 跳转到详情页
    });

    // 输入框回车键事件
    $('#searchQuery').keypress(function(e) {
      if (e.which === 13) { // 13 = Enter key
        handleSearch();
      }
    });
  }

  function handleSearch() {
    const query = $('#searchQuery').val().trim();

    // 输入验证
    if (!query) {
      showAlert('请输入搜索关键字', 'warning');
      return;
    }

    // 显示加载状态
    showLoading(true);

    // 发送请求
    $.ajax({
      url: '/dev/search',
      type: 'GET',
      dataType: 'json',
      data: { text: query },
      success: function(response) {
        handleSearchResponse(response);
      },
      error: function(xhr) {
        handleRequestError(xhr);
      },
      complete: function() {
        showLoading(false);
      }
    });
  }

  function handleSearchResponse(response) {
    if (response.code === "200") {
      if (response.data && response.data.length > 0) {
        renderSongList(response.data);
        $('#songList').slideDown(300);
      } else {
        showAlert('没有找到相关歌曲', 'info');
        $('#songList').slideUp(300);
      }
    } else {
      showAlert(`搜索失败: ${response.msg}`, 'danger');
    }
  }

  function renderSongList(songs) {
    const $tbody = $('#songs').empty();

    songs.forEach(song => {
      const row = createSongRow(song);
      $tbody.append(row);
    });
  }

  function createSongRow(song) {
    return `
    <tr class="song-item" data-song-id="${song.songId}"> <!-- 添加data属性保存ID -->
      <td class="song-title">${escapeHtml(song.title)}</td>
      <td class="artist">${escapeHtml(song.artist)}</td>
      <td class="album">${escapeHtml(song.album)}</td>
      <td class="duration">${formatDuration(song.duration)}</td>
    </tr>
  `;
  }

  function formatDuration(seconds) {
    if (!seconds || isNaN(seconds)) return '00:00';
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  }

  function handleRequestError(xhr) {
    let errorMsg = '请求失败: ';
    if (xhr.responseJSON && xhr.responseJSON.message) {
      errorMsg += xhr.responseJSON.message;
    } else {
      errorMsg += xhr.statusText;
    }
    showAlert(errorMsg, 'danger');
  }

  function showLoading(show) {
    if (show) {
      $('#loading').fadeIn(200);
      $('#songList').hide();
    } else {
      $('#loading').fadeOut(200);
    }
  }

  function showAlert(message, type = 'info') {
    const alert = $(`
        <div class="alert alert-${type} alert-dismissible fade in" role="alert"
             style="position: fixed; top: 20px; right: 20px; z-index: 9999;">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            ${message}
        </div>
    `);

    $('body').append(alert);
    setTimeout(() => alert.alert('close'), 3000);
  }

  // XSS防护
  function escapeHtml(unsafe) {
    return unsafe?.toString()
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;") || '';
  }

  // 添加CSS样式
  const dynamicStyles = `
    .song-item:hover {
        background-color: #f5f5f5;
        cursor: pointer;
    }
    .song-title {
        color: #337ab7;
        font-weight: 500;
    }
    #loading {
        text-align: center;
        padding: 15px;
        color: #666;
    }
`;
  $('<style>').html(dynamicStyles).appendTo('head');
</script>
</body>
</html>